package com.harvey.study.data.structure.datastructure.stack;

/**
 * 
 * date: 2021-04-26
 * desc: 顺序栈
 */
public class SequenceStack<T> {
    private final static int defaultSize = 10;//默认初始化栈表长度
    private T[] stackArray;
    private int top;//顶部指针位置

    public SequenceStack(int size) {
        if(size<=0){
            throw new RuntimeException("数据长度要大于1");
        }
        this.stackArray = (T[]) new Object[size];
        this.top = -1;
    }

    public SequenceStack() {
        this(defaultSize);
    }

    /**
     * 栈顶插入一个对象
     * @param data
     */
    public void push(T data){
        if(top == stackArray.length-1){
            expansion();
        }
        stackArray[++top] = data;
    }


    /**
     * 扩容
     */
    public void expansion(){
        T[] newArray = (T[]) new Object[stackArray.length*2];
        for(int i=0;i<stackArray.length;i++){
            newArray[i] = stackArray[i];
        }
        this.stackArray = newArray;
    }

    /**
     * 栈顶弹出一个对象
     * @return
     */
    public T pop(){
        if(isEmpty()){
            return null;
        }
        return stackArray[top--];
    }

    /**
     * 获取栈顶数据对象
     * @return
     */
    public T getHead(){
        if(isEmpty()){
            return null;
        }
        return stackArray[top];
    }

    /**
     * 判断栈是否为空
     * @return
     */
    public boolean isEmpty(){
        return top == -1;
    }

    /**
     * 栈长度
     * @return
     */
    public int size(){
        return top+1;
    }

    /**
     * 销毁一个已存在的栈
     */
    public void clear(){
        top = -1;
        stackArray = (T[]) new Object[defaultSize];
    }

    public static void main(String[] args) {
        SequenceStack<Integer> stack = new SequenceStack<Integer>();

        stack.push(1);
        stack.push(2);
        stack.push(3);
        stack.push(4);
        stack.push(1);
        stack.push(2);
        stack.push(3);
        stack.push(4);
        stack.push(1);
        stack.push(2);
        stack.push(3);
        stack.push(4);

        System.out.println(stack.size());
        System.out.println(stack.getHead());
        while(!stack.isEmpty()){
            System.out.println(stack.pop());
        }
        System.out.println(stack.size());
    }





    
    
}
